package com.shxc.smarttrade.old.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.StockChartDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.iview.IViewRealTimeQuote;
import com.shxc.smarttrade.old.iview.IViewStockChart;
import com.shxc.smarttrade.old.myview.CurrentTimeDrawing;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.MainPresenter;
import com.shxc.smarttrade.old.presenter.StockChartPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.wordplat.ikvstockchart.InteractiveKLineView;
import com.wordplat.ikvstockchart.KLineHandler;
import com.wordplat.ikvstockchart.compat.PerformenceAnalyser;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.entry.SizeColor;
import com.wordplat.ikvstockchart.marker.XAxisTextMarkerView;
import com.wordplat.ikvstockchart.marker.YAxisTextMarkerView;
import com.wordplat.ikvstockchart.render.KLineRender;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.mob.MobSDK.getContext;

/**
 * <p>StockChartActivity</p>
 * <p>Date: 2017/5/20</p>
 *
 * @author LYS
 */

public class StockChartActivity extends BaseActivity implements View.OnClickListener, IViewRealTimeQuote, IViewStockChart {
    private static final String TAG = "Activity";

    @BindView(R.id.k_line)
    InteractiveKLineView kLine;
    @BindView(R.id.pb_left)
    ProgressBar pbLeft;
    @BindView(R.id.ma_text)
    TextView maText;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_big_name)
    TextView tvBigName;
    @BindView(R.id.tv_little_name)
    TextView tvLittleName;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_pending)
    ImageView ivPending;
    @BindView(R.id.incloud_no)
    LinearLayout incloudNo;
    @BindView(R.id.incloud_yes)
    LinearLayout incloudYes;
    @BindView(R.id.btn_to_pending)
    Button btnToPending;
    @BindView(R.id.ll_footer)
    LinearLayout llFooter;
    @BindView(R.id.main_tv_buy_rise)
    TextView mainTvBuyRise;
    @BindView(R.id.main_tv_buy_fall)
    TextView mainTvBuyFall;

    //no_pending_order.xml
    @BindView(R.id.iv_set_lose_profit)
    ImageView ivSetLoseProfit;
    @BindView(R.id.ll_stop_lose)
    LinearLayout llStopLose;
    @BindView(R.id.ll_stop_profit)
    LinearLayout llStopProfit;
    @BindView(R.id.no_ll_orien)
    LinearLayout noLLOrien;
    @BindView(R.id.no_ll_buy_rise)
    LinearLayout noLLBuyRise;
    @BindView(R.id.no_ll_buy_fall)
    LinearLayout noLLBuyFall;
    @BindView(R.id.no_tv_buy_rise)
    TextView noTvBuyRise;
    @BindView(R.id.no_tv_buy_fall)
    TextView noTvBuyFall;
    @BindView(R.id.no_tv_center_times)
    TextView noTvCenterTimes;
    @BindView(R.id.no_tv_stop_loss_num)
    TextView noTVStopLossNum;
    @BindView(R.id.no_tv_stop_profit_num)
    TextView noTVStopProfitNum;
    @BindView(R.id.no_tv_stop_loss)
    TextView noTVStopLoss;
    @BindView(R.id.no_tv_stop_profit)
    TextView noTVStopProfit;

    //have_pending_order
    @BindView(R.id.have_ll_buy_rise)
    LinearLayout haveLLBuyRise;
    @BindView(R.id.have_ll_buy_fall)
    LinearLayout haveLLBuyFall;
    @BindView(R.id.have_tv_buy_rise)
    TextView haveTVBuyRise;
    @BindView(R.id.have_tv_buy_fall)
    TextView haveTVBuyFall;


    @BindView(R.id.tv_one)
    TextView tvOne;
    @BindView(R.id.tv_two)
    TextView tvTwo;
    @BindView(R.id.tv_three)
    TextView tvThree;
    @BindView(R.id.tv_four)
    TextView tvFour;
    @BindView(R.id.tv_five)
    TextView tvFive;
    @BindView(R.id.tv_six)
    TextView tvSix;
    @BindView(R.id.tv_seven)
    TextView tvSeven;
    @BindView(R.id.iv_tag)
    ImageView ivTag;
    @BindView(R.id.rl_left)
    LinearLayout rlLeft;

    //    private EntrySet entrySets;
    private int loadStartPos = 5500;
    private int loadEndPos = 6000;
    private int loadCount = 100;
    private boolean isPending = false;//是否挂单
    private boolean isSetLoseOrProfit = false;//是否设置止盈止损
    private int selectWhatNoPended = 0;//未开启挂单选择买涨还是买跌 0：买涨 1：买跌
    private int selectWhatHavePended = 0;//开启挂单后选择买涨还是买跌 0：买涨 1：买跌
    private double mStopProfit;//记录实时止盈的最值
    private double mStopLoss;//记录实时止损的最值

    private StockChartPresenter stockChartPresenter = new StockChartPresenter(this);
    private double noPendingTimes;//购买手数（待提交参数volume）
    private double minVolume;//手数每次减少和增加的量
    private double stopsLevel;//止盈止损远离步长
    private double stopLossOrProfitVar;//止盈止损的变化量
    private double stopLossTotal;//止损处总的改变量
    private double stopProfitTotal;//止盈处总的改变量

    private Animation animation = null;
    private int offset = 0;//游标的偏移量
    private int tagWidth = 0;//游标的宽度
    private int self = 0;//每块区域自身所在区域坐标
    private TextView textView = null;//当前被选中的TextView
    private String symbol = "";
    private MainPresenter mainPresenter = new MainPresenter(this);
    private long oldTime;//报价时间
    private double oldOpenPrice;//开盘价（某个时间段的）
    private double oldHigt;//最高价（某个时间段的）
    private double oldLow;//最低价（某个时间段的）
    private double oldClose;//收盘价（某个时间段的）
    private long timeDiff;//记录不同时间差
    private List<StockChartDatas.DataBean.QuotesBean> qb;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    StockChartDatas stockChartDatas = (StockChartDatas) msg.obj;
                    String errCode = stockChartDatas.getErr_code();
                    String errMsg = stockChartDatas.getErr_msg();
                    if (errCode.equals("0")) {
                        qb = stockChartDatas.getData().getQuotes();
                        if (qb == null || qb.size() == 0) return;
//                        Collections.reverse(qb);
                        oldTime = qb.get(qb.size() - 1).getTime();
                        oldOpenPrice = qb.get(qb.size() - 1).getOpenPrice();
                        oldHigt = qb.get(qb.size() - 1).getHigh();
                        oldLow = qb.get(qb.size() - 1).getLow();
                        oldClose = qb.get(qb.size() - 1).getClose();

                        EntrySet entrySet = new EntrySet();
                        for (int i = 0; i < qb.size(); i++) {

                            Long dataStr = qb.get(i).getTime();
                            String date = BaseUtils.millionToDate(dataStr);
                            entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), date));
                        }
                        PerformenceAnalyser.getInstance().addWatcher();
                        entrySet.computeStockIndex();
                        PerformenceAnalyser.getInstance().addWatcher();
                        kLine.setEntrySet(entrySet);
                        PerformenceAnalyser.getInstance().addWatcher();
                        KLineRender kr = (KLineRender) kLine.getRender();
                        kr.addDrawing(new CurrentTimeDrawing(BaseUtils.getScreenWidth(getApplicationContext())));
                        kLine.notifyDataSetChanged();
                        PerformenceAnalyser.getInstance().addWatcher();
                        if (!TextUtils.isEmpty(symbol)) {
                            stockChartPresenter.getSymboLCalInfo(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getApplicationContext(), "userId"));

                        }
                    } else {
                        showToast(errMsg);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_chart);

        initView();
        initListener();
        Intent intent = getIntent();
        symbol = intent.getStringExtra("symbol");
        String symbolCn = intent.getStringExtra("symbolCn");
        tvBigName.setText(symbolCn);
        tvLittleName.setText(symbol);
        showShortDialog();
        timeDiff = 1000 * 60;
        initDatas(symbol, 1);
    }

    /**
     * 初始化view
     */
    private void initView() {

        initBaseView();

        final int stockMarkerViewHeight = BaseUtils.dip2px(this, 15);
        KLineRender kLineRender = (KLineRender) kLine.getRender();
        //下面两行代码可以控制十字线两端是否有文本展示
        kLineRender.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight,2));
        kLineRender.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));
        kLine.setKLineHandler(new KLineHandler() {
            @Override
            public void onHighlight(Entry entry, int entryIndex, float x, float y) {
                final SizeColor sizeColor = kLine.getRender().getSizeColor();

                String maString = String.format(getResources().getString(R.string.ma_highlight),
                        entry.getMa5(),
                        entry.getMa10(),
                        entry.getMa20());

                maText.setText(getSpannableString(maString,
                        sizeColor.getMa5Color(),
                        sizeColor.getMa10Color(),
                        sizeColor.getMa20Color()));

            }

            @Override
            public void onCancelHighlight() {
                String maString = getResources().getString(R.string.ma_normal);
                maText.setText(maString);
            }

            @Override
            public void onSingleTap(MotionEvent e, float x, float y) {
                final KLineRender kLineRender = (KLineRender) kLine.getRender();

                if (kLineRender.getKLineRect().contains(x, y)) {
                    Toast.makeText(StockChartActivity.this, "single tab [" + x + ", " + y + "]", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onDoubleTap(MotionEvent e, float x, float y) {
                final KLineRender kLineRender = (KLineRender) kLine.getRender();

                if (kLineRender.getKLineRect().contains(x, y)) {
                    kLineRender.zoomIn(x, y);
                }
            }

            @Override
            public void onLeftRefresh() {
                pbLeft.setVisibility(View.VISIBLE);
                // 模拟耗时
                kLine.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pbLeft.setVisibility(View.GONE);

                        List<Entry> entries = insertEntries();

                        kLine.getRender().getEntrySet().insertFirst(entries);
                        kLine.notifyDataSetChanged();
                        kLine.refreshComplete(true);

                        if (entries.size() == 0) {
                            Toast.makeText(StockChartActivity.this, "已经到达最左边了", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, 1000);
            }

            @Override
            public void onRightRefresh() {
                kLine.notifyDataSetChanged();
            }
        });
    }

    /**
     * 初始化基础View
     */
    private void initBaseView() {
        tvBigName.setText("欧元美元");
        tvLittleName.setText("EURUSD");
        tvRight.setText("品种介绍");
        textView = tvOne;
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivTag.getLayoutParams();
        params.width = screenWidth / 7;
        ivTag.setLayoutParams(params);
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        ivTag.setImageMatrix(matrix);// 设置动画初始位置
        tagWidth = screenWidth / 7;
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        rlLeft.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        ivPending.setOnClickListener(this);
        ivSetLoseProfit.setOnClickListener(this);
        tvOne.setOnClickListener(this);
        tvTwo.setOnClickListener(this);
        tvThree.setOnClickListener(this);
        tvFour.setOnClickListener(this);
        tvFive.setOnClickListener(this);
        tvSix.setOnClickListener(this);
        tvSeven.setOnClickListener(this);
        noLLBuyRise.setOnClickListener(this);
        noLLBuyFall.setOnClickListener(this);
        haveLLBuyRise.setOnClickListener(this);
        haveLLBuyFall.setOnClickListener(this);
    }

    private SpannableString getSpannableString(String str, int partColor0, int partColor1, int partColor2) {
        String[] splitString = str.split("[●]");
        SpannableString spanString = new SpannableString(str);

        int pos0 = splitString[0].length();
        int pos1 = pos0 + splitString[1].length() + 1;
        int pos2 = pos1 + splitString[2].length() + 1;
        int end = str.length();

        spanString.setSpan(new ForegroundColorSpan(partColor0),
                pos0, pos1, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor1),
                pos1, pos2, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor2),
                pos2, end, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        return spanString;
    }

    /**
     * 初始化K线图历史数据
     *
     * @param symbol
     */
    private void initDatas(String symbol, int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(this, "accessToken", ""));
        map.put("symbol", symbol);
        map.put("type", type + "");
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.STOCK_CHART_ACTIVITY_HISTORYQUOTE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(R.string.net_error);
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                Gson gson = new Gson();
                StockChartDatas scd = gson.fromJson(response, StockChartDatas.class);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = scd;
                handler.sendMessage(msg);
                dismissShortDialog();
            }
        });
    }


    /**
     * 往K线图中插入数据,用于滑动加载更多（暂时无用）
     *
     * @return
     */
    private List<Entry> insertEntries() {
        List<Entry> entries = new ArrayList<>();

//        int insertCount = 0;
//        for (int i = loadStartPos; i > loadStartPos - loadCount && i > -1; i--) {
//            insertCount++;
//
//            entries.add(entrySet.getEntryList().get(i));
//        }
//        loadStartPos -= insertCount;

        return entries;
    }

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, StockChartActivity.class);
        return intent;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.tv_right:
                break;
            case R.id.iv_pending://是否挂单按钮
                btnToPending.setText("确定挂单");
                if (isPending) {
                    if (selectWhatNoPended == 0) {
                        btnToPending.setText("确定买涨");
                    } else {
                        btnToPending.setText("确定买跌");
                    }
                    incloudNo.setVisibility(View.VISIBLE);
                    llFooter.setVisibility(View.VISIBLE);
                    incloudYes.setVisibility(View.GONE);
                    btnToPending.setVisibility(View.GONE);
                    ivPending.setImageResource(R.mipmap.btn_normal);
                    isPending = false;
                    if (isSetLoseOrProfit) {
                        llStopLose.setVisibility(View.VISIBLE);
                        llStopProfit.setVisibility(View.VISIBLE);
                        noLLOrien.setVisibility(View.VISIBLE);
                        btnToPending.setVisibility(View.VISIBLE);
                        llFooter.setVisibility(View.GONE);
                        ivSetLoseProfit.setImageResource(R.mipmap.btn_click);
                    } else {
                        llStopLose.setVisibility(View.GONE);
                        llStopProfit.setVisibility(View.GONE);
                        noLLOrien.setVisibility(View.GONE);
                        btnToPending.setVisibility(View.GONE);
                        llFooter.setVisibility(View.VISIBLE);
                        ivSetLoseProfit.setImageResource(R.mipmap.btn_normal);
                    }

                } else {
                    incloudNo.setVisibility(View.GONE);
                    llFooter.setVisibility(View.GONE);
                    incloudYes.setVisibility(View.VISIBLE);
                    btnToPending.setVisibility(View.VISIBLE);
                    ivPending.setImageResource(R.mipmap.btn_click);
                    isPending = true;
                }
                break;
            case R.id.iv_set_lose_profit://是否设置止盈止损按钮
                if (selectWhatNoPended == 0) {
                    btnToPending.setText("确定买涨");
                } else {
                    btnToPending.setText("确定买跌");
                }
                if (isSetLoseOrProfit) {
                    llStopLose.setVisibility(View.GONE);
                    llStopProfit.setVisibility(View.GONE);
                    noLLOrien.setVisibility(View.GONE);
                    btnToPending.setVisibility(View.GONE);
                    llFooter.setVisibility(View.VISIBLE);
                    ivSetLoseProfit.setImageResource(R.mipmap.btn_normal);
                    isSetLoseOrProfit = false;
                } else {
                    llStopLose.setVisibility(View.VISIBLE);
                    llStopProfit.setVisibility(View.VISIBLE);
                    noLLOrien.setVisibility(View.VISIBLE);
                    btnToPending.setVisibility(View.VISIBLE);
                    llFooter.setVisibility(View.GONE);
                    ivSetLoseProfit.setImageResource(R.mipmap.btn_click);
                    isSetLoseOrProfit = true;
                }
                break;
            case R.id.tv_one:
                goAnimation(0);
                setTabTextColors(tvOne, textView);
                textView = tvOne;
                break;
            case R.id.tv_two:
                goAnimation(1);
                setTabTextColors(tvTwo, textView);
                textView = tvTwo;
                break;
            case R.id.tv_three:
                goAnimation(2);
                setTabTextColors(tvThree, textView);
                textView = tvThree;
                break;
            case R.id.tv_four:
                goAnimation(3);
                setTabTextColors(tvFour, textView);
                textView = tvFour;
                showShortDialog();
                timeDiff = 1000 * 60;
                initDatas(symbol, 1);
                break;
            case R.id.tv_five:
                goAnimation(4);
                setTabTextColors(tvFive, textView);
                textView = tvFive;
                showShortDialog();
                timeDiff = 1000 * 60 * 5;
                initDatas(symbol, 5);
                break;
            case R.id.tv_six:
                goAnimation(5);
                setTabTextColors(tvSix, textView);
                textView = tvSix;
                showShortDialog();
                timeDiff = 1000 * 60 * 15;
                initDatas(symbol, 15);
                break;
            case R.id.tv_seven:
                goAnimation(6);
                setTabTextColors(tvSeven, textView);
                textView = tvSeven;
                showShortDialog();
                timeDiff = 1000 * 60 * 30;
                initDatas(symbol, 30);
                break;
            case R.id.no_ll_buy_rise://未开启挂单后选择买涨还是买跌
                stopLossTotal = 0;//止损的增量归零
                stopProfitTotal = 0;//止盈的增量归零
                noTVStopLossNum.setText("没有设置");
                noTVStopProfitNum.setText("没有设置");
                btnToPending.setText("确定买涨");
                noLLBuyRise.setBackgroundResource(R.mipmap.bg_red_checked);
                noLLBuyFall.setBackgroundResource(R.mipmap.bg_no_check);
                selectWhatNoPended = 0;
                break;
            case R.id.no_ll_buy_fall://未开启挂单后选择买涨还是买跌
                stopLossTotal = 0;//止损的增量归零
                stopProfitTotal = 0;//止盈的增量归零
                noTVStopLossNum.setText("没有设置");
                noTVStopProfitNum.setText("没有设置");
                btnToPending.setText("确定买跌");
                noLLBuyRise.setBackgroundResource(R.mipmap.bg_no_check);
                noLLBuyFall.setBackgroundResource(R.mipmap.bg_red_checked);
                selectWhatNoPended = 1;
                break;
            case R.id.have_ll_buy_rise://开启挂单后选择买涨还是买跌
                haveLLBuyRise.setBackgroundResource(R.mipmap.bg_red_checked);
                haveLLBuyFall.setBackgroundResource(R.mipmap.bg_no_check);
                selectWhatHavePended = 0;
                break;
            case R.id.have_ll_buy_fall://开启挂单后选择买涨还是买跌
                haveLLBuyRise.setBackgroundResource(R.mipmap.bg_no_check);
                haveLLBuyFall.setBackgroundResource(R.mipmap.bg_red_checked);
                selectWhatHavePended = 1;
                break;

        }
    }

    /**
     * 执行动画
     */
    private void goAnimation(int tagPosi) {
        if (tagPosi == 0) {
            self = 0;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = 0;
        } else if (tagPosi == 1) {
            self = tagWidth;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth;
        } else if (tagPosi == 2) {
            self = tagWidth * 2;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 2;
        } else if (tagPosi == 3) {
            self = tagWidth * 3;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 3;
        } else if (tagPosi == 4) {
            self = tagWidth * 4;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 4;
        } else if (tagPosi == 5) {
            self = tagWidth * 5;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 5;
        } else if (tagPosi == 6) {
            self = tagWidth * 6;
            animation = new TranslateAnimation(offset, self, 0, 0);//四参构造函数：第一个参数表述表示动画开始的点离当前View X坐标上的差值！！！差值！！！差值！！！
            offset = tagWidth * 6;
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(200);
        ivTag.startAnimation(animation);
    }

    /**
     * 设置Tab文本的字体颜色
     */
    private void setTabTextColors(TextView tv1, TextView tv2) {
        if (tv1 != tv2) {
            tv1.setTextColor(getResources().getColor(R.color.main_color));
            tv2.setTextColor(getResources().getColor(R.color.secondary_text_color));
        }
    }

    /**
     * 接收实时数据
     *
     * @param quoteBeen
     */
    @Override
    public void setData(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        if (quoteBeen.size() > 0) {
            //用于展示页面上的的基本数据
            double ask = quoteBeen.get(0).getAsk();
            double bid = quoteBeen.get(0).getBid();
            mainTvBuyRise.setText("买涨 " + ask);
            mainTvBuyFall.setText("买跌 " + bid);

            noTvBuyRise.setText(ask + "");
            noTvBuyFall.setText(bid + "");

            haveTVBuyRise.setText(ask + "");
            haveTVBuyFall.setText(bid + "");

            //当开启止盈止损时
            if (isSetLoseOrProfit) {
                if (selectWhatNoPended == 0) {
                    //买涨
                    mStopProfit = Arith.add(ask, stopsLevel);
                    mStopLoss = Arith.sub(ask, stopsLevel);
                    noTVStopProfit.setText("> " + mStopProfit);
                    noTVStopLoss.setText("< " + mStopLoss);
                } else {
                    //买跌
                    mStopProfit = Arith.sub(bid, stopsLevel);
                    mStopLoss = Arith.add(bid, stopsLevel);
                    noTVStopLoss.setText("> " + mStopLoss);
                    noTVStopProfit.setText("< " + mStopProfit);
                }


            }

            Long newTime = quoteBeen.get(0).getTime();
            Double market = quoteBeen.get(0).getMarket();
            String newData = BaseUtils.millionToDate(newTime);

            if (newTime - oldTime < timeDiff) {
                oldHigt = Math.max(market, oldHigt);
                oldLow = Math.min(market, oldLow);
                oldClose = market;
                //更改最后一个数据
                changeLastData(newData);

            } else {
                oldTime = newTime;
                oldOpenPrice = market;
                oldHigt = market;
                oldLow = market;
                oldClose = market;
                //增加一条新数据
//                Log.e("日期", oldData + "");
                Log.e("entry.size", kLine.getRender().getEntrySet().getEntryList().size() + "");
                EntrySet entrySett = new EntrySet();
                entrySett.addEntry(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));
                entrySett.computeStockIndex();
                List<Entry> entriess = entrySett.getEntryList();
                kLine.getRender().getEntrySet().addEntries(entriess);
                kLine.notifyDataSetChanged();
            }

        }

    }

    /**
     * 实时更改最后一条数据
     *
     * @param newData
     */
    private void changeLastData(String newData) {
        EntrySet entrySets = new EntrySet();
        List<Entry> en = kLine.getRender().getEntrySet().getEntryList();
        en.remove(en.size() - 1);
        en.add(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));
        entrySets.addEntries(en);
        entrySets.computeStockIndex();
        kLine.setEntrySet(entrySets);
        kLine.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainPresenter.stopRealTimerQuote();
    }

    private MyProgressDialog dialog;

    @Override
    public void showDialog() {
        dialog = new MyProgressDialog(this);
        dialog.show();
    }

    @Override
    public void dismissDialog() {
        dialog.dismiss();
    }

    @Override
    public void showMyToast(String str) {
        showToast(str);
    }

    /**
     * 品种保证金及止盈止损数据
     *
     * @param symbolInfo
     */
    @Override
    public void setSymbolCalInfoData(SymbolInfo symbolInfo) {
        if (!TextUtils.isEmpty(symbol)) {
            mainPresenter.startRealTimeQuote(symbol);
        }
        noTvCenterTimes.setText(symbolInfo.getMinVolume() + "");
        minVolume = symbolInfo.getMinVolume();
        noPendingTimes = symbolInfo.getMinVolume();
        stopsLevel = (double) symbolInfo.getStopsLevel();
        Log.e("symbolInfo.getDigits()", symbolInfo.getDigits() + "");
        double dd = Math.pow(10, symbolInfo.getDigits());
        Log.e("dd", dd + "");
        stopLossOrProfitVar = Arith.round3(Arith.div(1, dd), symbolInfo.getDigits());
        Log.e("stopLossOrProfitVar", stopLossOrProfitVar + "");
    }

    @Override
    public void setTradeOpenData(OpenTrader openTrader) {

    }

    @Override
    public void setPendingOrderData(PendingOrder pendingOrder) {

    }

    @Override
    public void setSymbolPrice(SymbolPrice symbolPrice) {

    }

    /**
     * 未设置挂单中减少交易手数按钮
     */
    @OnClick(R.id.no_iv_left_sub)
    public void noIVLeftSub() {
        if (noPendingTimes > minVolume) {
            noPendingTimes = Arith.sub(noPendingTimes, minVolume);
            noTvCenterTimes.setText(noPendingTimes + "");
        }

    }

    /**
     * 未设置挂单中增加交易手数按钮
     */
    @OnClick(R.id.no_iv_right_add)
    public void noIVRightAdd() {
        //先判断可买的最大手数，当满足条件后才执行下面操作
        noPendingTimes = Arith.add(noPendingTimes, minVolume);
        noTvCenterTimes.setText(noPendingTimes + "");

    }

    private double sl = 0;//待提交参数（止损价）
    private double tp = 0;//待提交参数（止盈价）

    /**
     * 未挂单开启止盈止损：止损 减
     */
    @OnClick(R.id.no_iv_stop_loss_sub)
    public void noIVStopLossSub() {
        stopLossTotal = Arith.sub2(stopLossTotal, stopLossOrProfitVar);
        //判断当前是买涨还是买跌
        if (selectWhatNoPended == 0) { //买涨
            sl = Arith.add(mStopLoss, stopLossTotal);
            noTVStopLossNum.setText(sl + "");

        } else { //买跌
            if (stopLossTotal > 0) {
                sl = Arith.add(mStopLoss, stopLossTotal);
                noTVStopLossNum.setText(sl + "");
            }

        }
    }

    /**
     * 未挂单开启止盈止损：止损 加
     */
    @OnClick(R.id.no_iv_stop_loss_add)
    public void noIVStopLossAdd() {
        stopLossTotal = Arith.add(stopLossTotal, stopLossOrProfitVar);
        if (selectWhatNoPended == 0) { //买涨
            if (stopLossTotal < 0) {
                sl = Arith.add(mStopLoss, stopLossTotal);
                noTVStopLossNum.setText(sl + "");
            }

        } else {//买跌
            sl = Arith.add(mStopLoss, stopLossTotal);
            noTVStopLossNum.setText(sl + "");

        }
    }

    /**
     * 未挂单开启止盈止损：止盈 减
     */
    @OnClick(R.id.no_iv_stop_profit_sub)
    public void noIVStopoProfitSub() {
        stopProfitTotal = Arith.sub2(stopProfitTotal, stopLossOrProfitVar);

        if (selectWhatNoPended == 0) {//买涨
            if (stopProfitTotal > 0) {
                tp = Arith.add(mStopProfit, stopProfitTotal);
                noTVStopProfitNum.setText(tp + "");
            }
        } else {//买跌

            tp = Arith.add(mStopProfit, stopProfitTotal);
            noTVStopProfitNum.setText(tp + "");
        }
    }

    /**
     * 未挂单开启止盈止损：止盈 加
     */
    @OnClick(R.id.no_iv_stop_profit_add)
    public void noIVStopProfitAdd() {
        stopProfitTotal = Arith.add(stopProfitTotal, stopLossOrProfitVar);

        if (selectWhatNoPended == 0) {//买涨
            tp = Arith.add(mStopProfit, stopProfitTotal);
            noTVStopProfitNum.setText(tp + "");
        } else {//买跌
            if (stopProfitTotal < 0) {
                tp = Arith.add(mStopProfit, stopProfitTotal);
                noTVStopProfitNum.setText(tp + "");
            }
        }
    }

    /**
     * 确定挂单、确定买跌、确定买涨三个按钮合一
     */
    @OnClick(R.id.btn_to_pending)
    public void btnToPendings() {
        if (isPending) {
            //处理挂单逻辑

        } else {
            //取消挂单下的按钮
            if (selectWhatNoPended == 0) {//买涨
                //处理买涨逻辑
                stockChartPresenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(this, "userId"), selectWhatNoPended, (float) noPendingTimes, tp, sl);
            } else {//买跌
                //处理买跌逻辑
                stockChartPresenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(this, "userId"), selectWhatNoPended, (float) noPendingTimes, tp, sl);
            }

        }
    }

    /**
     * 直接买涨按钮
     */
    @OnClick(R.id.main_ll_buy_rise)
    public void mainLLBuyRise() {
        View view = View.inflate(this, R.layout.dialog_under_margin, null);
        TextView btnGoRecharge = (TextView) view.findViewById(R.id.btn_go_recharge);
        TextView btnEnsure = (TextView) view.findViewById(R.id.btn_ensure);
        btnGoRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        showPopupWindow(view);
    }

    /**
     * 直接买跌按钮
     */
    @OnClick(R.id.main_ll_buy_fall)
    public void mainLLBuyFall() {

    }

    /**
     * 显示操作对话框
     *
     * @param mainView
     */
    public void showPopupWindow(View mainView) {
        PopupWindow popupWindow = new PopupWindow(mainView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.AnimationBottonAndTop);
        popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_stock_chart, null), Gravity.BOTTOM, 0, 0);
        setBackgroundAlpha(0.7f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
            }
        });
    }

    /**
     * 设置popupwindow背景色
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

}
